<template>
  <div class="user-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span>用户管理 /</span>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="showAddDialog">+ 添加用户</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户姓名：">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入用户姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号：">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="部门：">
          <el-select
            v-model="searchForm.departmentId"
            placeholder="请选择部门"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="dept in departmentOptions"
              :key="dept.id"
              :label="dept.label"
              :value="dept.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 内容整体容器 -->
    <div class="content-wrapper">
      <!-- 表格区域 -->
      <div class="table-wrapper">
        <el-table :data="userList" stripe style="width: 100%" size="medium">
          <el-table-column
            prop="name"
            label="姓名"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="username"
            label="用户名"
            align="center"
          ></el-table-column>
          <el-table-column prop="avatar" label="头像" width="80" align="center">
            <template #default="scope">
              <div class="avatar-wrapper">
                <!-- 检查多种可能的头像字段名 -->
                <img
                  :src="getUserAvatar(scope.row)"
                  style="width: 40px; height: 40px; border-radius: 50%"
                  alt="用户头像"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="部门" align="center">
            <template #default="scope">
              {{ getDepartmentName(scope.row.deptId) || "-" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="roleName"
            label="角色"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="phone"
            label="手机号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            width="100"
            align="center"
          >
            <template #default="scope">
              <div class="status-wrapper">
                <span
                  :style="{
                    color: scope.row.status === 1 ? '#666666' : '#D9001B',
                  }"
                >
                  {{ formatUserStatus(scope.row.status) }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="updateTime"
            label="最后操作时间"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="action"
            label="操作"
            width="150"
            align="center"
          >
            <template #default="scope">
              <el-button type="text" @click="showEditDialog(scope.row)"
                >修改</el-button
              >
              <el-button
                type="text"
                @click="showDeleteDialog(scope.row.id)"
                style="color: #ff4d4f"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="closeDialog"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="userForm"
        label-width="100px"
        validate-on-rule-change
        status-icon
        validate-event
        hide-required-asterisk
      >
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px">
          <el-form-item label="用户名：" prop="username">
            <el-input
              v-model="formData.username"
              placeholder="请输入用户名"
              maxlength="20"
              :validate-event="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名：" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入姓名"
              maxlength="20"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号：" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机号"
              maxlength="11"
              @blur="validatePhone"
              :validate-event="true"
            ></el-input>
            <div
              v-if="errors.phone"
              class="el-form-item__error"
              style="margin-top: 0"
            >
              {{ errors.phone }}
            </div>
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱"
              maxlength="50"
              @blur="validateEmail"
              :validate-event="true"
            ></el-input>
            <div
              v-if="errors.email"
              class="el-form-item__error"
              style="margin-top: 0"
            >
              {{ errors.email }}
            </div>
          </el-form-item>
          <el-form-item label="性别：" prop="gender">
            <el-select v-model="formData.gender" placeholder="请选择性别">
              <el-option
                v-for="option in genderOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态">
              <el-option
                v-for="option in userStatusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="部门：" prop="departmentId">
            <el-select
              v-model="formData.departmentId"
              placeholder="请选择部门"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="dept in departmentOptions"
                :key="dept.id"
                :label="dept.label"
                :value="dept.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色：" prop="roleId">
            <el-select
              v-model="formData.roleId"
              placeholder="请选择角色"
              clearable
            >
              <el-option
                v-for="role in roleOptions"
                :key="role.id"
                :label="role.label"
                :value="role.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- 头像单独一行 -->
        <el-form-item label="头像：" prop="image">
          <div style="display: flex; align-items: center">
            <el-upload
              class="avatar-uploader"
              :action="'/api/upload'"
              :headers="getHeaders()"
              name="image"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="formData.image" :src="formData.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-hint" style="margin-left: 20px">
              图片上传，支持扩展名：png/jpg/jpeg，大小限制：2M
            </div>
          </div>
        </el-form-item>

        <!-- 备注单独一行 -->
        <el-form-item label="备注：" prop="remark">
          <el-input
            v-model="formData.remark"
            placeholder="请输入用户的备注信息，最多50字"
            maxlength="50"
            show-word-limit
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog title="删除确认" v-model="deleteDialogVisible" width="300px">
      <span>确定要删除该用户吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { useUserStore } from "@/stores/user";
import { useDepartmentStore } from "@/stores/department";
import { useRoleStore } from "@/stores/role";
import { useAuthStore } from "@/stores/auth";
import {
  userStatusOptions,
  genderOptions,
  formatUserStatus,
  formatGender,
} from "@/utils/sysUtils";
import { computed, reactive, ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import request from "@/api/request";

export default {
  name: "UserView",
  setup() {
    // 初始化store
    const userStore = useUserStore();
    const departmentStore = useDepartmentStore();
    const roleStore = useRoleStore();
    const authStore = useAuthStore();

    // 搜索表单
    const searchForm = reactive({
      name: "",
      phone: "",
      departmentId: "",
      status: "",
    });

    // 分页相关
    const currentPage = ref(1);
    const pageSize = ref(10);

    // 对话框相关
    const dialogVisible = ref(false);
    const dialogTitle = ref("添加用户");
    const formData = reactive({
      id: "",
      username: "",
      name: "",
      phone: "",
      email: "",
      gender: 1, // 使用数字值而非字符串
      status: 1, // 使用数字值而非字符串
      departmentId: "",
      roleId: "",
      remark: "",
      image: "", // 头像字段，对应后端的image字段
    });
    // 头像相关变量

    const deleteDialogVisible = ref(false);
    const deleteId = ref("");
    const userForm = ref(null);

    // 错误信息存储
    const errors = reactive({
      username: "",
      phone: "",
      email: "",
    });

    // 计算属性 - 从store获取数据
    const userList = computed(() => userStore.getUsers);
    const total = computed(() => userStore.getTotal);
    const departmentOptions = computed(
      () => departmentStore.getDepartmentOptions
    );
    const roleOptions = computed(() => roleStore.getRoleOptions);
    const isLoading = computed(() => userStore.isLoading);

    // 验证用户名唯一性
    const validateUsernameUnique = (rule, value, callback) => {
      if (!value) {
        return callback();
      }

      const exists = userList.value.some(
        (user) => user.username === value && user.id !== formData.id
      );

      if (exists) {
        callback(new Error("用户名已存在"));
      } else {
        callback();
      }
    };

    // 验证手机号唯一性
    const validatePhoneUnique = (rule, value, callback) => {
      if (!value) {
        return callback();
      }

      const exists = userList.value.some(
        (user) => user.phone === value && user.id !== formData.id
      );

      if (exists) {
        callback(new Error("手机号已存在"));
      } else {
        callback();
      }
    };

    // 验证邮箱唯一性
    const validateEmailUnique = (rule, value, callback) => {
      if (!value) {
        return callback();
      }

      const exists = userList.value.some(
        (user) => user.email === value && user.id !== formData.id
      );

      if (exists) {
        callback(new Error("邮箱已存在"));
      } else {
        callback();
      }
    };

    // 表单验证规则
    const formRules = {
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        {
          pattern: /^[a-zA-Z0-9_]{2,20}$/,
          message: "用户名必须为2-20位，只能包含字母、数字和下划线",
          trigger: "blur",
        },
        { validator: validateUsernameUnique, trigger: "blur" },
      ],
      name: [
        { required: true, message: "请输入姓名", trigger: "blur" },
        {
          pattern: /^.{2,20}$/,
          message: "姓名必须为2-20位",
          trigger: "blur",
        },
      ],
      phone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        {
          pattern: /^1[3-9]\d{9}$/,
          message: "手机号必须为11位有效数字",
          trigger: "blur",
        },
        { validator: validatePhoneUnique, trigger: "blur" },
      ],
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { min: 5, max: 50, message: "邮箱长度应在5-50位之间", trigger: "blur" },
        {
          pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
          message: "请输入有效的邮箱地址",
          trigger: "blur",
        },
        { validator: validateEmailUnique, trigger: "blur" },
      ],
      gender: [{ required: true, message: "请选择性别", trigger: "change" }],
      status: [{ required: true, message: "请选择状态", trigger: "change" }],
      remark: [{ max: 50, message: "备注长度不能超过50位", trigger: "blur" }],
    };
    // 加载用户列表
    const loadUserList = async () => {
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        name: searchForm.name,
        phone: searchForm.phone,
        deptId: searchForm.departmentId,
        status: searchForm.status ? Number(searchForm.status) : undefined,
      };
      await userStore.loadUserList(params);
    };

    // 加载部门和角色数据
    const loadBaseData = async () => {
      await Promise.all([
        departmentStore.loadAllDepartments(),
        roleStore.loadAllRoles(),
      ]);
    };

    // 初始化数据
    onMounted(async () => {
      await loadBaseData();
      await loadUserList();
    });

    // 搜索
    const search = () => {
      currentPage.value = 1;
      loadUserList();
    };

    // 重置搜索
    const resetSearch = () => {
      searchForm.name = "";
      searchForm.phone = "";
      searchForm.departmentId = "";
      searchForm.status = "";
      currentPage.value = 1;
      loadUserList();
    };

    // 显示添加对话框
    const showAddDialog = () => {
      dialogTitle.value = "添加用户";
      formData.id = "";
      formData.username = "";
      formData.name = "";
      formData.phone = "";
      formData.email = "";
      formData.gender = 1;
      formData.status = 1;
      formData.departmentId = "";
      formData.roleId = "";
      formData.remark = "";
      formData.image = "";
      dialogVisible.value = true;
    };

    // 显示编辑对话框
    const showEditDialog = (row) => {
      dialogTitle.value = "修改用户";
      formData.id = row.id;
      formData.username = row.username;
      formData.name = row.name;
      formData.phone = row.phone;
      formData.email = row.email;
      formData.gender = row.gender;
      formData.status = row.status;
      formData.departmentId = row.deptId;
      formData.roleId = row.roleId;
      formData.remark = row.remark || "";
      formData.image = row.image || "";
      dialogVisible.value = true;
    };

    // 关闭对话框
    const closeDialog = () => {
      dialogVisible.value = false;
      if (userForm.value) {
        userForm.value.resetFields();
      }
    };

    // 头像上传成功处理
    const handleAvatarSuccess = (response) => {
      // 根据接口文档，返回的data字段直接是图片URL
      if (response.code === 1) {
        formData.image = response.data;
        ElMessage.success("头像上传成功");
      } else {
        ElMessage.error("头像上传失败：" + (response.msg || "未知错误"));
      }
    };

    // 获取请求头，安全处理token
    const getHeaders = () => {
      try {
        return {
          token: authStore.token || "",
        };
      } catch (error) {
        return {};
      }
    };

    // 验证上传的文件
    const beforeAvatarUpload = (rawFile) => {
      const isPNG = rawFile.type === "image/png";
      const isJPG = rawFile.type === "image/jpeg";
      const isJPEG = rawFile.type === "image/jpeg";

      if (!isPNG && !isJPG && !isJPEG) {
        ElMessage.error("上传头像图片只能是 png/jpg/jpeg 格式!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      return true;
    };

    // 自定义手机号验证
    const validatePhone = () => {
      errors.phone = "";
      if (!formData.phone) {
        errors.phone = "请输入手机号";
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
        errors.phone = "手机号必须为11位有效数字";
        return false;
      }

      // 唯一性验证
      const exists = userList.value.some(
        (user) => user.phone === formData.phone && user.id !== formData.id
      );
      if (exists) {
        errors.phone = "手机号已存在";
        return false;
      }
      return true;
    };

    // 自定义邮箱验证
    const validateEmail = () => {
      errors.email = "";
      if (!formData.email) {
        errors.email = "请输入邮箱";
        return false;
      }
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
        errors.email = "请输入有效的邮箱地址";
        return false;
      }

      // 唯一性验证
      const exists = userList.value.some(
        (user) => user.email === formData.email && user.id !== formData.id
      );
      if (exists) {
        errors.email = "邮箱已存在";
        return false;
      }
      return true;
    };

    // 提交表单
    const submitForm = async () => {
      if (!userForm.value) return;

      // 手动触发验证
      const phoneValid = validatePhone();
      const emailValid = validateEmail();

      if (!phoneValid || !emailValid) {
        ElMessage.error("请修正表单中的错误");
        return;
      }

      try {
        const userData = {
          id: formData.id,
          username: formData.username,
          name: formData.name,
          phone: formData.phone,
          email: formData.email,
          gender: formData.gender,
          status: formData.status,
          deptId: formData.departmentId ? Number(formData.departmentId) : null,
          roleId: formData.roleId ? Number(formData.roleId) : null,
          remark: formData.remark,
          image: formData.image,
        };

        let result;
        if (formData.id) {
          // 修改用户
          result = await userStore.updateUser(userData);
        } else {
          // 添加用户
          result = await userStore.addUser(userData);
          if (result.success) {
            // 添加成功后显示初始密码提示
            ElMessage.success(`添加成功，初始密码为：${formData.username}123`);
          }
        }

        if (result.success) {
          closeDialog();
        }
      } catch (error) {
      }
    };

    // 显示删除确认对话框
    const showDeleteDialog = (id) => {
      deleteId.value = id;
      deleteDialogVisible.value = true;
    };

    // 确认删除
    const confirmDelete = async () => {
      try {
        const result = await userStore.deleteUser(deleteId.value);
        if (result.success) {
          ElMessage.success("删除成功");
          deleteDialogVisible.value = false;
        }
      } catch (error) {
      }
    };

    // 分页相关
    const handleSizeChange = (size) => {
      pageSize.value = size;
      currentPage.value = 1;
      loadUserList();
    };

    const handleCurrentChange = (current) => {
      currentPage.value = current;
      loadUserList();
    };
    // 根据部门ID获取部门名称
    const getDepartmentName = (deptId) => {
      if (!deptId) return "";
      const department = departmentStore.getDepartments.find(
        (dept) => dept.id === deptId
      );
      return department ? department.name : "";
    };

    // 获取用户头像，优先使用image字段
    const getUserAvatar = (user) => {
      // 定义默认头像
      const defaultAvatar =
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";

      // 根据用户提供的信息，优先检查image字段
      if (user && user.image) {
        return user.image;
      }

      // 检查其他可能的头像字段名作为备选
      if (
        user &&
        (user.avatar || user.avatarUrl || user.avatar_url || user.img)
      ) {
        return user.avatar || user.avatarUrl || user.avatar_url || user.img;
      }

      // 如果没有头像数据，返回默认头像
      return defaultAvatar;
    };

    // 暴露给模板的数据和方法
    return {
      // 响应式数据
      searchForm,
      currentPage,
      pageSize,
      dialogVisible,
      dialogTitle,
      formData,
      deleteDialogVisible,
      deleteId,
      userForm,
      errors,
      // 计算属性
      userList,
      total,
      departmentOptions,
      roleOptions,
      isLoading,
      // 选项数据
      userStatusOptions,
      genderOptions,
      // 格式化函数
      formatUserStatus,
      formatGender,
      // 方法
      search,
      resetSearch,
      showAddDialog,
      showEditDialog,
      closeDialog,
      submitForm,
      getHeaders,
      showDeleteDialog,
      confirmDelete,
      handleSizeChange,
      handleCurrentChange,
      getDepartmentName,
      getUserAvatar,
      handleAvatarSuccess,
      beforeAvatarUpload,
    };
  },
};
</script>

<style scoped>
.user-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
  color: #606266;
}

.operation-area {
  margin-bottom: 20px;
}

/* 搜索条件区域 */
.search-container {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px 20px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

/* 确保表单内所有元素在一行 */
:deep(.el-form--inline) {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  width: 100%;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 15px;
  margin-bottom: 0;
}

/* 按钮样式调整 */
:deep(.el-form--inline .el-form-item:last-child) {
  margin-left: auto;
  margin-right: 0;
}

/* 调整输入框和选择器的宽度 */
:deep(.el-input__wrapper) {
  min-width: 160px;
}

:deep(.el-select) {
  min-width: 160px;
}

/* 内容整体容器 */
.content-wrapper {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  margin-bottom: 20px;
  flex: 1;
}

/* 表格内容容器 */
.table-wrapper {
  overflow-x: auto; /* 允许水平滚动 */
  overflow-y: auto; /* 允许垂直滚动 */
  height: 400px; /* 固定高度确保滚动条出现 */
  border-bottom: 1px solid #ebeef5;
}

/* 分页容器 */
.pagination-wrapper {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 15px 20px;
  background-color: #fff;
  clear: both;
  position: relative;
  z-index: 10;
  box-sizing: border-box;
  width: 100%;
}

/* 调整表格样式 */
:deep(.el-table) {
  border-top: none;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #606266;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

/* 头像容器样式，确保对齐 */
.avatar-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

/* 状态容器样式，确保对齐 */
.status-wrapper {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  text-align: center;
}

/* 确保表格在小屏幕上也能正常显示 */
@media (max-width: 768px) {
  .user-container {
    padding: 10px;
  }

  .search-container {
    padding: 15px;
  }

  .el-form--inline .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .table-wrapper {
    overflow-x: scroll;
  }
}
/* 头像上传组件样式 */
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #1e406f;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
